<template>
  <a-upload
      v-model:file-list="fileList"
      name="avatar"
      list-type="picture-card"
      class="avatar-uploader"
      :show-upload-list="false"
      :customRequest="customRequest"
  >
    <img v-if="imageUrl" :src="imageUrl" alt="avatar" style="width: 100px; height: 100px;border-radius: 8px"/>

    <div v-else>
      <loading-outlined v-if="loading"></loading-outlined>
      <plus-outlined v-else></plus-outlined>
    </div>
  </a-upload>
</template>

<script setup lang="ts">
import {ref, watch} from 'vue';
import {LoadingOutlined, PlusOutlined} from '@ant-design/icons-vue';
import {FileApi} from "~/api/system/file.api";

const fileList = ref([]);
const loading = ref<boolean>(false);
const imageUrl = ref<string>('');
const api = new FileApi();
const emits = defineEmits(['update','update:value'])
const props = defineProps({
  value: {
    type: String,
    default: undefined
  }
})

function customRequest(e: any) {
  loading.value = true;
  api.onImageFile(e.file).then(resp => {
    if (resp.ok) {
      imageUrl.value = resp.data as any;
      emits('update:value', imageUrl.value)
      emits('update', imageUrl.value)
    }
  }).finally(()=>{
    loading.value = false;
  })
}

watch(props, value => {
  if(value.value){
    imageUrl.value = value.value;
  }
}, {immediate: true})
</script>

<style scoped lang="scss">
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}

.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
